﻿using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class GUIPanel {
	// === Public =====================================================================================================
	public static GUIPanel CreateInstance() {
		var instance = new GUIPanel();
		return instance;
	}

	public void ShowPanel(GUIPanelType type) {
		if (CheckOpenPanel(type)) {
			return;
		}
		CreateGoElement(type);
	}

	public void HideAllPanelAndShowPanel(GUIPanelType type) {
		HidePanels();
		CreateGoElement(type);
	}

	public void HidePanels(List<GUIPanelElement> elements = null) {
		var list = elements ?? new List<GUIPanelElement>(_goElementTypes);
		foreach (var element in list) {
			HidePanel(element);
		}
	}

	public void HidePanel(GUIPanelElement element) {
		Object.Destroy(element.GameObject);
		_goElementTypes.Remove(element);
	}

	public void HidePanel(GUIPanelType type) {
		var element = _goElementTypes.FirstOrDefault(panelElement => panelElement.ElementType.Equals(type));
		if (element == null) {
			return;
		}
		Object.Destroy(element.GameObject);
		_goElementTypes.Remove(element);
	}

	// === Private ====================================================================================================
	private readonly List<GUIPanelElement> _goElementTypes = new List<GUIPanelElement>();

	private bool CheckOpenPanel(GUIPanelType type) {
		return _goElementTypes.Any(goElementType => type.Equals(goElementType.ElementType));
	}

	private void CreateGoElement(GUIPanelType type) {
		var prefab = Tools.Prefab.GetPrefab(type);
		var goElement = Tools.Prefab.Create<GameObject>(prefab);
		var element = new GUIPanelElement {
			ElementType = type,
			GameObject = goElement
		};
		_goElementTypes.Add(element);
	}
}